package com.jstyle.jclife.adapter;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.jstyle.jclife.NetWork.NetWorkUtil;
import com.jstyle.jclife.R;
import com.jstyle.jclife.activity.BindDeviceActivity;
import com.jstyle.jclife.activity.BindDeviceListActivity;
import com.jstyle.jclife.ble.BleManager;
import com.jstyle.jclife.daoManager.BindDeviceInfoDaoManager;
import com.jstyle.jclife.model.BindDeviceInfo;
import com.jstyle.jclife.model.BleData;

import com.jstyle.jclife.model.Device1810;
import com.jstyle.jclife.model.JstyleDevice;
import com.jstyle.jclife.model.NetResultData;
import com.jstyle.jclife.utils.NetWorkConast;
import com.jstyle.jclife.utils.RxBus;
import com.jstyle.jclife.utils.SchedulersTransformer;
import com.jstyle.jclife.utils.SharedPreferenceUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Created by Administrator on 2019/4/1.
 */

public class BindDeviceInfoAdapter extends RecyclerViewBaseAdapter<BindDeviceInfo> {

    int checkPosition = 0;
    private int REQUEST_ENABLE_BT = 2;


    public BindDeviceInfoAdapter(List<BindDeviceInfo> bindDeviceInfos) {
        super(bindDeviceInfos);
    }

    public void setCheckPosition(int postion) {
        this.checkPosition = postion;
        notifyDataSetChanged();
    }

    private static final String TAG = "BindDeviceInfoAdapter";
    @Override
    protected void bindData(BaseViewHolder holder, final int position) {
        BindDeviceInfoHolder bindDeviceInfoHolder = (BindDeviceInfoHolder) holder;
        final Context context = ((BindDeviceInfoHolder) holder).itemView.getContext();

        final BindDeviceInfo bindDeviceInfo = mDataList.get(position);
        setDeviceType(bindDeviceInfo);
        String name = bindDeviceInfo.getDeviceName();
        final String address = bindDeviceInfo.getMacAddress();
        final String selectedAddress = SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_ADDRESS);
        final boolean isSelected = address.equals(selectedAddress);
        if (isSelected) {//当前选中的设备
            if (!TextUtils.isEmpty(updateVersion)) {
                bindDeviceInfo.setDeviceVersion(updateVersion);
                BindDeviceInfoDaoManager.updateData(bindDeviceInfo);
            }
            boolean isConnected = BleManager.getInstance().isConnected();
            bindDeviceInfoHolder.btDeviceState.setText(isConnected ? R.string.device_connected : R.string.device_disconnected);
            bindDeviceInfoHolder.ivDeviceRssi.setImageResource(isConnected ? R.drawable.rssi_level : R.drawable.bind_not_selected);
        } else {
            bindDeviceInfoHolder.ivDeviceRssi.setImageResource(R.drawable.bind_not_selected);
            bindDeviceInfoHolder.btDeviceState.setText(R.string.device_disconnected);
        }

        String version = bindDeviceInfo.getDeviceVersion();
        bindDeviceInfoHolder.tvDeviceTitle.setText(name);
        bindDeviceInfoHolder.tvDeviceAddress.setText(address);
        bindDeviceInfoHolder.tvDeviceVersion.setText("Firmware Version:V" + version);
        bindDeviceInfoHolder.imageView2.setImageResource(bindDeviceInfo.getJstyleDevice().getConnectDrawableId());
        bindDeviceInfoHolder.btUnbindDevice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                disconnectOldDevice(context, bindDeviceInfo, position, isSelected);
            }
        });
        ((BindDeviceInfoHolder) holder).itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!BleManager.getInstance().isBleEnable()) {
                    enableBle(context);
                    return;
                }

                if (!isSelected) {
                    SharedPreferenceUtils.setSpString(SharedPreferenceUtils.KEY_ADDRESS, address);
                    broadcastUpdate(BindDeviceListActivity.ActionDeviceChange, address);
                    if (BleManager.getInstance().isConnected()) {
                        BleManager.getInstance().disconnectDevice();
                    } else {
                        BleManager.getInstance().connectDevice(address, true);
                    }
                    // notifyDataSetChanged();
                }
            }
        });
    }

    private void unBindDevice(String serNumber) {
        String uid = NetWorkUtil.getUserId();
        NetWorkUtil.getInstance().getJstyleApi().bindDevice(uid, serNumber, NetWorkConast.UNBIND)
                .compose(SchedulersTransformer.<NetResultData>io2MainObservable())
                .subscribe(new Observer<NetResultData>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NetResultData netResultData) {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    protected void enableBle(Context context) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        ((Activity) context).startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }

    private void disconnectOldDevice(final Context context, final BindDeviceInfo bindDeviceInfo, final int position, final boolean isSelected) {
        AlertDialog dialog = new AlertDialog.Builder(context, R.style.appalertdialog)

                .setMessage(context.getString(R.string.whether_ubind)).
                        setNegativeButton(context.getString(R.string.cancel), null)
                .setPositiveButton(context.getString(R.string.ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (!NetWorkUtil.isNetworkConnected(context)) {
                            Toast.makeText(context, context.getString(R.string.network_bad), Toast.LENGTH_SHORT).show();
                            return;
                        }
                        String serNumber=bindDeviceInfo.getSerialNumber();
                        if(!TextUtils.isEmpty(serNumber)){
                            unBindDevice(serNumber);
                        }
                        BindDeviceInfoDaoManager.deleteDeviceInfo(bindDeviceInfo.getMacAddress());
                        mDataList.remove(position);
                        if (isSelected) {

                            BleManager.getInstance().disconnectDevice();
                            if (mDataList.size() == 0) {
                                SharedPreferenceUtils.setSpString(SharedPreferenceUtils.KEY_ADDRESS, "");
                                Intent intent = new Intent(context, BindDeviceActivity.class);
                                context.startActivity(intent);
                                ((Activity) context).finish();
                            } else {
                                String nextAddress = mDataList.get(0).getMacAddress();
                                SharedPreferenceUtils.setSpString(SharedPreferenceUtils.KEY_ADDRESS, nextAddress);
                                BleManager.getInstance().connectDevice(nextAddress);
                            }

                        }

                        notifyDataSetChanged();

                    }
                }).create();
        dialog.show();
//        ScreenUtils.setDialogButtonTextColor(dialog);

    }

    private void setDeviceType(BindDeviceInfo bindDeviceInfo) {
        JstyleDevice jstyleDevice = bindDeviceInfo.getJstyleDevice();
        String name = bindDeviceInfo.getDeviceName();
        if (!TextUtils.isEmpty(name)) {
            if (name.contains(JstyleDevice.device_1810)) {
                jstyleDevice = new Device1810();
            }
        }
        bindDeviceInfo.setJstyleDevice(jstyleDevice);
    }

    private void broadcastUpdate(String action, String address) {
        BleData bleData = new BleData();
        bleData.setAction(action);
        bleData.setData(address);
        RxBus.getInstance().post(bleData);
    }

    String updateVersion;

    public void updateVersion(String version) {
        updateVersion = version;
        notifyDataSetChanged();
    }

    @Override
    public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(getLayoutId(viewType), parent, false);
        return new BindDeviceInfoHolder(view);
    }

    public class BindDeviceInfoHolder extends BaseViewHolder {
        @BindView(R.id.imageView2)
        ImageView imageView2;
        @BindView(R.id.tv_device_title)
        TextView tvDeviceTitle;
        @BindView(R.id.tv_device_version)
        TextView tvDeviceVersion;
        @BindView(R.id.tv_device_address)
        TextView tvDeviceAddress;
        @BindView(R.id.iv_device_rssi)
        ImageView ivDeviceRssi;
        @BindView(R.id.bt_device_state)
        TextView btDeviceState;
        @BindView(R.id.bt_unbind_device)
        Button btUnbindDevice;
        @BindView(R.id.rl_device)
        ConstraintLayout rlDevice;

        public BindDeviceInfoHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    @Override
    protected int getLayoutId(int viewType) {
        return R.layout.item_binddevice_info;
    }


}
